package org.jkuang.qstar.commons.io;

public class StopDeCoder {
	private int size;
	private int offset;
	private byte[] buffer;
	private boolean reverse;
	static final int ch8f = 0x8f;
	static final int chc0 = 0xc0;

	public StopDeCoder(byte[] buffer, int size, boolean reverse) {
		this.size = size;
		this.buffer = buffer;
		this.reverse = reverse;
		if (reverse) {
			this.offset = size;
		} else {
			this.offset = 0;
		}
	}

	public long next() {
		if (reverse) {
			return reverseValue();
		} else {
			return nextValue();
		}
	}

	private long nextValue() {
		long v = 0;
		if (this.offset >= size) {
			return 0;
		}
		while (++this.offset < size && buffer[this.offset] > 0)
			;
		int offset = this.offset;
		while (offset-- >= 0) {
			if (buffer[offset] < 0) {
				v = v << 6 | (buffer[offset] & 0x3f);
				if (buffer[offset] >> 6 == -1) {
					return -v;
				} else {
					return v;
				}
			} else {
				v = v << 7 | buffer[offset];
			}
		}
		return v;
	}

	private long reverseValue() {
		long v = 0;
		while (offset-- >= 0) {
			if (buffer[offset] < 0) {
				v = v << 6 | (buffer[offset] & 0x3f);
				if (buffer[offset] >> 6 == -1) {
					return -v;
				} else {
					return v;
				}
			} else {
				v = v << 7 | buffer[offset];
			}
		}
		return v;
	}
}
